﻿#include <QtGui>
#include <QDialog>
#include <QtNetwork/QTcpSocket>
#include <QHostAddress>
//#include <sys/socket.h>
#include <QTcpServer>
#include "form.h"
#include "ui_form.h"
#include "dialog.h"
#include "user_control.h"

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    pixmap=new QPixmap();

    this->socket=NULL;
    ui->pushButton->setEnabled(true);//开启视频按钮的初值给true
    ui->pushButton_2->setEnabled(false);//关闭视频按钮的初值给false
    this->setMinimumSize(640,480);
    this->setMaximumSize(640,480);
    ui->label->setMinimumSize(480,320);
    ui->label->setMaximumSize(480,320);
}

Form::~Form()
{
    delete ui;
}

void Form::on_pushButton_clicked()
{
    if(this->socket == NULL)
    {
     this->socket = new QTcpSocket();

     this->socket->connectToHost("192.168.1.165",8888);
    //发送信号者为socket这个实例，发送的信号是connected(),接收者为Form,槽函数为msconnected()



     connect(this->socket,SIGNAL(connected()),this,SLOT(msconnected()));
     connect(this->socket,SIGNAL(disconnected()),this,SLOT(msdisconnected()));
     //发送信号者为socket这个实例，发送的信号是error(QAbstractSocket::SocketError),接收者为Form,槽函数为error()
     //connect(this->socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(error()));
     ui->pushButton->setEnabled(false);//开启视频后让此按钮变灰
     ui->pushButton_2->setEnabled(true);//已经开启视频后让关闭视频按钮变黑（true）

    }
    else
    {
        ui->pushButton->setEnabled(false);
        ui->pushButton_2->setEnabled(true);
        timer->start(100);
    }
}

void Form::msconnected()
{
    qDebug() << "connected";
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(updatepic()));
    timer->start(100);

}

void Form::msdisconnected()
{
    if(timer->isActive())
        timer->stop();
    ui->pushButton->setEnabled(true);//按下关闭视频按钮后让开启视频按钮变黑（true）
    ui->pushButton_2->setEnabled(false);//按下关闭视频按钮后让关闭按钮变灰（false）
    this->socket->close();
    this->socket = NULL;
}

void Form::updatepic()
{
    int ret;
    char *request = "pic";      //请求命令
    char response[20];          //服务器发给QT的回复
    char *len;                  //
    unsigned int piclen;        //图片长度
    char picbuf[1024 * 1024];   //存放图片



    ret = this->socket->write(request, strlen(request));  //发送请求图片命令
    if (ret != strlen(request)) {
        qDebug() << "send request failed";
        timer->stop();
        this->socket->close();
    }

    this->socket->flush();    //刷新socket
    this->socket->waitForReadyRead(30000);

    memset(response, 0, sizeof(response));
    ret = this->socket->read(response, sizeof(response));
    if (ret != sizeof(response)) {
        qDebug() << "recv response failed";
        timer->stop();
        this->socket->close();
        this->socket = NULL;
    }

    len = strstr(response, "len");
    if (len == NULL) {
        qDebug() << "response header is error";
        timer->stop();
        this->socket->close();
        this->socket = NULL;
    }

    *len = '\0';
    //从response中读取图片长度
    piclen = atoi(response);

    qDebug() << "piclen: " << piclen;

    int total = 0;
    //循环读取pic信息
    while (total < piclen) {
        ret = this->socket->read(picbuf+total, piclen-total);
        if (ret < 0) {
            qDebug() << "recv pic failed" << ret;
            timer->stop();
            this->socket->close();
            this->socket = NULL;
            return;
        } else if (ret == 0) {
            this->socket->waitForReadyRead(30000);
            continue;
        } else
            total += ret;

        qDebug() << "total: " << total;
    }

    pixmap->loadFromData((const uchar *)picbuf, piclen, "JPEG");
    ui->label->setPixmap(*pixmap);
}


void Form::on_pushButton_2_clicked()
{
    qDebug() << "total:----11--------------- ";
    if(timer->isActive())
        timer->stop();
   qDebug() << "total:------------------- ";
    ui->pushButton->setEnabled(true);//按下关闭视频按钮后让开启视频按钮变黑（true）
    ui->pushButton_2->setEnabled(false);//按下关闭视频按钮后让关闭按钮变灰（false）
}

void Form::on_pushButton_3_clicked()
{
    this->dialog2.show();
}
